<template>
    <div class="flex w100  jcsb recruit_top">
        <div class="flex aic jcsb recruit_top_left">
            <div class="fontz fonts18">
                招聘人数(人)
            </div>
            <div class="fontz fonts36 fontw700">
                <span>{{ state.recruitmentNumber }}</span>
            </div>
        </div>
        <div class=" recruit_top_right">
            <div class="flex">
                <div @click="navClick(2)" class="h100 recruit_top_navs flex flex_c jcc aic"
                    :class="state.navValue == 2 ? 'recruit_top_nav' : ''">
                    <p class="fonts24">{{ state.positionNumber }}</p>
                    <p class="fonts14">在招职位</p>
                </div>
                <div @click="navClick(1)" class="h100 recruit_top_navs flex flex_c jcc aic"
                    :class="state.navValue == 1 ? 'recruit_top_nav' : ''">
                    <p class="fonts24">{{ state.auditPositionNumber }}</p>
                    <p class="fonts14">待审核职位</p>
                </div>
                <div @click="navClick(0)" class="h100 recruit_top_navs flex flex_c jcc aic"
                    :class="state.navValue == 0 ? 'recruit_top_nav' : ''">
                    <p class="fonts24">{{ state.closePositionNumber }}</p>
                    <p class="fonts14">已关闭职位</p>
                </div>
            </div>
        </div>
    </div>
    <ContentWrap>
        <!-- <h2 class="fonts24 fontw500">短信管理</h2> -->
        <div class="flex justify-between">
            <div class="flex aic">
                <ElInput v-model="state.ruleForm.positionName" style="width: 266px;height: 32px;margin-right: 26px;"
                    placeholder="职位名称" :prefix-icon="Search" clearable />
                <el-cascader v-model="state.ruleForm.deptId" clearable placeholder="应聘部门" :options="state.options"
                    :props="props1" />
                <!-- <el-select clearable v-model="state.ruleForm.keywords" placeholder="审核状态" style="margin-right: 16px;margin-left: 16px;">
                    <el-option label="Zone one" value="shanghai" />
                    <el-option label="Zone two" value="beijing" />
                </el-select> -->
                <ElButton type="primary" :icon="Search" @click="onSearch" style="margin-left: 16px;">
                    查询
                </ElButton>
                <ElButton :icon="Refresh" @click="onReset">
                    重置
                </ElButton>
                <ElButton type="primary" @click="onClose" v-if="state.navValue != 0">
                    一键关闭
                </ElButton>
                <ElButton type="primary" @click="onOpen" v-if="state.navValue == 0">
                    一键启用
                </ElButton>
                <ElButton type="primary" :icon="Plus" @click="onAdd">
                    新增招聘职位
                </ElButton>
                <el-upload class="upload-demo" action="/api/enterprise/position/importData" multiple
                    :headers="state.headers" :before-upload="beforeAvatarUpload" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <ElButton type="primary" style="margin: 0px 16px 0px 16px;" :icon="Upload">
                        批量新增职位
                    </ElButton>
                </el-upload>

                <ElButton type="primary" :icon="Download" @click="downloadFun">
                    下载模板
                </ElButton>
                <ElButton type="primary" :icon="Position" @click="shareFun">
                    批量分享
                </ElButton>
            </div>
        </div>
        <div class="" style="margin-top: 25px;" v-if="true">
            <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
                :data="dataList" :loading="loading" :pagination="{ total: total }" @register="tableRegister"
                :headerCellStyle="headerCellStyle" :rowStyle="rowStyle" />
        </div>
        <Kong title="您还没有在招职位" v-else-if="false" />
        <DeteleVue ref="formChildrenRefs" :deteleData="state.deteleData" @deteleClick="deteleClick" />
    </ContentWrap>
    <Dialog v-model="dialogVisible1" :title="state.fromTitle" width="900" style="overflow: auto;">
      <RecruitFrom :data="state.ruleForms" @FormClick="FormClick" :title="state.fromTitle" />
    </Dialog>
    <Dialog v-model="dialogVisible3" title="分享职位" width="350" style="overflow: hidden;">
        <div class="flex" style="flex-direction: column;padding: 0px 0 20px 0;">
            <p class="" style="padding: 16px 0;"> <span style="color: #1c53d9;">{{ state.shareData.companyName
                    }}</span>的热招职位!</p>
            <ShareVue :data="state.shareData" @qrCodeBoxClick="qrCodeBoxClick" />
            <p class="" style="padding: 16px 0 10px 0;">链接地址：</p>
            <p><span class="" style="color: #1c53d9;">{{ state.shareData.url }}</span></p>
            <div class="flex" style="padding: 16px 0 10px 0;">
                <ElButton type="primary" @click="copyEr">
                    下载二维码
                </ElButton>
                <ElButton type="primary" @click="copyUrl">
                    复制地址链接
                </ElButton>
            </div>
        </div>
    </Dialog>
    <Dialog v-model="dialogVisible4" title="投递详情" width="900" style="overflow: hidden;">
        <div class="" style="height: 70vh;overflow-y: auto;">
            <PositionDetail :positionId="state.positionId" />
        </div>
    </Dialog>
</template>

<script setup lang="tsx">
import { urlData } from '@/utils/url'; 
import { RecruitFrom, ShareVue, PositionDetail } from "./components/index"
import { Kong } from "@/components/Kong/index"
import { DeteleVue } from "@/components/Detele/index"
import { getdepartmentlist } from "@/api/department/index"
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { Search, Plus, Refresh, Pointer, Star, Upload, Download, Position } from '@element-plus/icons-vue'
import { Form, FormSchema } from '@/components/Form'
import { Dialog } from '@/components/Dialog'
import { useEmitt } from '@/hooks/event/useEmitt'
import { ElButton, ElInput, ElMessage, ElMessageBox } from 'element-plus'
// import { propTypes } from '@/utils/propTypes'
import { useI18n } from '@/hooks/web/useI18n'
import { ContentWrap } from '@/components/ContentWrap'
import { ref, reactive, unref } from "vue"
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { positionList, downloadTemplate, addpositionApi, editpositionApi, editPositionStatusApi, deletepositionApi, del, positionHeaderList } from "@/api/recruit/index"
import { deptTreeList } from "@/api/organizational/index"
import { formatToDateTime } from "@/utils/dateUtil"
import type { UploadProps, UploadUserFile } from 'element-plus'
import axios from 'axios';
import config from '@/config/axios/config'
import { useStorage } from '@/hooks/web/useStorage'
import { useAppStoreWithOut } from '@/store/modules/app'
const { defaultHeaders } = config
const { getStorage } = useStorage()
const appStore = useAppStoreWithOut()
const userInfo = getStorage(appStore.getUserInfo)
const { required } = useValidator()
const { formRegister, formMethods } = useForm()
const { getElFormExpose } = formMethods
const { t } = useI18n()
const props1 = {
    checkStrictly: true,
    value: "id",
    label: "label",
    emitPath: false
}
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const dialogVisible3 = ref(false)
const dialogVisible4 = ref(false)
const formChildrenRefs = ref()
const state = reactive({
    positionId: "",
    headers: {
        "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
        "clientid": userInfo ? userInfo.client_id : "e5cd7e4891bf95d1d19206ce24a7b32e"
    },
    ruleForm: {} as any,
    ruleForms: {} as any,
    react: false,
    navValue: 2,
    deteleData: {//删除框
        content: "",
        title: "",
        sure: true,
        closeValue: true,
        knowBool: false
    },
    fromTitle: "",
    options: [] as any,
    status: 2 as any,
    delId: "",
    recruitmentNumber: 0,
    positionNumber: 0,
    closePositionNumber: 0,
    auditPositionNumber: 0,
    shareData: {} as any,

})
const FormClick = (value) => {
    dialogVisible1.value = false
    if (value == 0) {
        getList()
    }

}
// 表格基本信息
const crudSchemas = reactive<CrudSchema[]>([
    {
        field: 'selection',
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            type: 'selection'
        }
    },
    {
        field: 'positionName',
        label: t('职位名称'),
        search: {
            component: 'Input'
        },
        form: {
            component: 'Input',
            colProps: {
                span: 24
            }
        },
        detail: {
            span: 24
        }
    },
    {
        field: 'deptName',
        label: t('应聘部门'),

    },
    {
        field: 'username',
        label: t('薪资范围'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.salaryStart + data[0].row.salaryUnit + "-" + data[0].row.salaryEnd + data[0].row.salaryUnit + "x" + data[0].row.salaryRange + "月"}</div>
                        </>
                    )
                }
            }
        }
    }, {
        field: 'recruitmentNumber',
        label: t('招聘人数'),

    }, {
        field: 'admissionNumber',
        label: t('已入职人数'),
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.admissionNumber ? data[0].row.admissionNumber : "0"}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'recruitmentDeadline',
        label: t('招聘截止日期'),
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.recruitmentDeadline ? data[0].row.recruitmentDeadline.slice(0,16) : "无"}</div>
                        </>
                    )
                }
            }
        }
    }, {
        field: 'createByNickName',
        label: t('创建人'),
        search: {
            hidden: true
        }
    },
    {
        field: 'create_time',
        label: t('平台审核状态'),
        search: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <div>{data[0].row.status == 0 ? "未通过" : data[0].row.status == 1 ? "待审核" : data[0].row.status == 2 ? "已审核" : "已关闭"}</div>
                        </>
                    )
                }
            }
        }
    },
    {
        field: 'action',
        width: '320px',
        label: t('tableDemo.action'),
        search: {
            hidden: true
        },
        form: {
            hidden: true
        },
        detail: {
            hidden: true
        },
        table: {
            slots: {
                default: (data: any) => {
                    return (
                        <>
                            <ElButton link type="primary" onClick={() => action(data[0].row)}>
                                修改
                            </ElButton>
                            <ElButton link type="primary" onClick={() => actions(data[0].row)}>
                                查看
                            </ElButton>
                            <ElButton link type="primary" onClick={() => getShow(data[0].row)}>
                                分享
                            </ElButton>
                            <ElButton link type="danger" onClick={() => detele(data[0].row)}>
                                删除
                            </ElButton>
                            <ElButton link type="primary" onClick={() => getDetail(data[0].row)}>
                                投递详情
                            </ElButton>
                        </>
                    )
                }
            }
        }
    }
])
const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
        positionHeaderListApi()
        const { currentPage, pageSize } = tableState
        const res: any = await positionList({
            pageNum: state.react ? 1 : unref(currentPage),
            pageSize: unref(pageSize),
            positionName: state.ruleForm.positionName,
            deptId: state.ruleForm.deptId,
            status: state.status
        })
        console.log(res);
        state.react = false
        return {
            list: res.rows,
            total: res.total
        }
    }
})
// 表格头部信息
const headerCellStyle: any = {
    "background": "#F2F6FC",
    "height": "48px"
}
// 
const rowStyle: any = {
    "height": "48px"
}
const { loading, dataList, total, currentPage, pageSize } = tableState

const { getList, getElTableExpose, delList } = tableMethods

getList()
useEmitt({
    name: 'getList',
    callback: (type: string) => {
        if (type === 'add') {
            currentPage.value = 1
        }
        getList()
    }
})
const { allSchemas } = useCrudSchemas(crudSchemas)
const onAdd = () => {
    dialogVisible1.value = true
    state.ruleForms = {
        welfareTreatment: []
    }
    state.fromTitle = "新增招聘职位"
}
const onAdds = () => {
    console.log("批量新增职位");
    dialogVisible2.value = true
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile.type);
    if (rawFile.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        ElMessage.error('图片格式有误! 仅支持xlxs格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('上传文件支持10M以内!')
        return false
    }
    return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    console.log(response);
    ElMessage.success(response.msg)
    getList()
}
const downloadFun = () => {
    downloadTemplate().then(res => {
        console.log("下载", res);
        const link = document.createElement('a');
        link.href = res.data;
        link.setAttribute('download', res.data);
        link.click();
    })
    // zipFun(`/api/enterprise/position/downloadTemplate`, "excal")
}
const shareFun = async () => {
    console.log("分享职位！！");
    const elTableRef = await getElTableExpose()
    const selections = elTableRef?.getSelectionRows()
    console.log(selections)
    if (selections.length == 0) {
        ElMessage({
            type: 'warning',
            message: `请选择需要分享的职位`,
        })
    } else {
        let positionIds = []
        let companyName=""
        selections.forEach(item => {
            positionIds.push(item.id)
            companyName=item.tenantVo.companyName
        })
        const urls = urlData.sharePostionUrl
        let obj = {
            companyName: companyName,
            url: urls + "pages/index/position/sharePosition/sharePosition?showBool=1&positionIds=" + positionIds
        }
        state.shareData = obj
        dialogVisible3.value = true
    }


}
const getDetail = (row: any) => {
    console.log("投递详情", row);
    dialogVisible4.value = true
    state.positionId = row.id
}
const zipFun = async (url: string, fileType: string) => {
    const userInfo = getStorage(appStore.getUserInfo)
    // ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' });
    try {
        const res: any = await axios({
            method: 'get',
            url: url,
            responseType: 'blob',
            headers: {
                'Content-Type': defaultHeaders,
                "Authorization": `Bearer ${userInfo ? userInfo.access_token : ""}`,
                "clientid": userInfo ? userInfo.client_id : "d4dc82f7317e7c0482d95f764930e587"
            }
        });
        console.log("下载职位模板：", res);
        // let blob = null as any
        // if (fileType == "word") {
        //     blob = new Blob([res.data], { type: 'application/zip' })
        // } else {
        //     blob = new Blob([res.data], { type: "application/vnd.ms-excel" })
        // }
        const href = URL.createObjectURL(res.data)
        const link = document.createElement('a')
        link.download = '职位模板'
        link.href = href
        link.click()
        URL.revokeObjectURL(href);
        document.body.removeChild(link);
        // ElLoading.service({text: '下载成功', background: 'rgba(0, 0, 0, 0.7)'}).close()
    } catch {

    }
}


const action = (row: any) => {
    state.fromTitle = "编辑招聘职位"
    console.log("编辑", row);
    state.ruleForms = row
    dialogVisible1.value = true
}
const actions = (row: any) => {
    state.fromTitle = "查看招聘职位"
    // console.log("编辑", row);
    state.ruleForms = row
    dialogVisible1.value = true
}
const navClick = (index) => {
    state.navValue = index
    state.status = index
    // if (state.navValue == 0) {
    //     state.status = 2
    // } else if (state.navValue == 1) {
    //     state.status = 1
    // } else {
    //     state.status = 0
    // }
    onReset()
}
const getShow = (row: any) => {
    console.log("分享：", row);
    const urls = urlData.sharePostionUrl
    let obj = {
        companyName: row.tenantVo.companyName,
        url: urls + "pages/index/position/sharePosition/sharePosition?showBool=0&positionId=" + row.id
    }
    state.shareData = obj
    dialogVisible3.value = true
}
const imageUrl = ref("")
const qrCodeBoxClick = async (value) => {
    imageUrl.value = value
}
const copyEr = async () => {
    downloadBase64Img(imageUrl.value, "二维码")

}
function downloadBase64Img(base64URL, fileName) {
    // 创建a标签，用于触发下载  
    const a = document.createElement('a');
    // 将 a 标签的 download 属性设置为要下载的文件名  
    a.download = fileName || 'image';
    // 创建 Blob 对象，并获取 base64 数据的 MIME 类型  
    const mimeType = base64URL.match(/:(.*?);/)[1];
    // 将 base64 数据转换为字节数组  
    const byteCharacters = atob(base64URL.split(',')[1]);
    const byteNumbers = new Array(byteCharacters.length);
    // 将字节数组填充到 Uint8Array 中  
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    // 创建 Blob 对象  
    const blob = new Blob([byteArray], { type: mimeType });
    // 将 Blob 对象的 URL 赋值给 a 标签的 href 属性  
    a.href = URL.createObjectURL(blob);
    // 将a标签暂时添加到 body 中，触发下载  
    document.body.appendChild(a);
    a.click();
    // 下载完成后，将 a 标签从 body 中移除  
    document.body.removeChild(a);
}

const copyUrl = async () => {
    const aux = document.createElement('input')
    aux.setAttribute('value', state.shareData.url)
    document.body.appendChild(aux)
    aux.select()
    document.execCommand('copy')
    document.body.removeChild(aux)
    ElMessage({
        type: 'success',
        message: `文本已复制到剪贴板！`,
    })
    // try {
    //     await navigator.clipboard.writeText(state.shareData.url);
    //     ElMessage({
    //         type: 'success',
    //         message: `文本已复制到剪贴板！`,
    //     })
    // } catch (error) {
    //     ElMessage({
    //         type: 'error',
    //         message: `复制失败!`,
    //     })
    // }

}
// 查询
const onSearch = () => {
    console.log("查询");
    state.react = true
    getList()
}
// 重置
const onReset = () => {
    console.log("重置");
    state.ruleForm = {}
    state.react = true
    getList()
}
// 一键关闭
const onClose = async () => {
    console.log("一键关闭");
    const elTableRef = await getElTableExpose()
    const selections = elTableRef?.getSelectionRows()
    console.log(selections)
    if (selections.length == 0) {
        ElMessage({
            type: 'warning',
            message: `请选择需要关闭的职位`,
        })
    } else {
        let array = []
        selections.forEach(item => {
            array.push(item.id)
        })
        let obj = {
            "ids": array,
            "status": "0"
        }
        editPositionStatusApi(obj).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
            positionHeaderListApi()
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }
}
const onOpen = async () => {
    console.log("一键启用");
    const elTableRef = await getElTableExpose()
    const selections = elTableRef?.getSelectionRows()
    console.log(selections)
    if (selections.length == 0) {
        ElMessage({
            type: 'warning',
            message: `请选择需要启用的职位`,
        })
    } else {
        let array = []
        selections.forEach(item => {
            array.push(item.id)
        })
        let obj = {
            "ids": array,
            "status": "1"
        }
        editPositionStatusApi(obj).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
            positionHeaderListApi()
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }
}

// const detele = (row) => {
//     state.delId=row.id
//     if (formChildrenRefs.value) {
//         formChildrenRefs.value.DialogOpen()
//     }
// }
// const deteleClick = (value) => {
//     if (value) {
//         console.log("确定删除！",value);
//         if (formChildrenRefs.value) {
//             formChildrenRefs.value.DialogClose()
//         }
//     }
// }
const detele = (row: any) => {
    ElMessageBox.confirm('确认删除该职位？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // inputPattern:,
        draggable: true,
        type: 'warning',
    }).then(() => {
        deletepositionApi(row.id).then((res: any) => {
            getList()
            ElMessage({
                type: 'success',
                message: `${res.msg}`,
            })
        }).catch((res: any) => {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消操作',
        })
    })
}
// 
const onKnow = () => {
    dialogVisible1.value = false
}
const deptTreeListApi = async () => {
    await deptTreeList().then(res => {
        state.options = res.data.tree
    })
}
deptTreeListApi()
const positionHeaderListApi = async () => {
    await positionHeaderList().then(res => {
        console.log("header", res);
        state.closePositionNumber = res.data.closePositionNumber
        state.positionNumber = res.data.positionNumber
        state.recruitmentNumber = res.data.recruitmentNumber
        state.auditPositionNumber = res.data.auditPositionNumber
    })
}
// positionHeaderListApi()

</script>

<style lang="less" scoped>
.message_p {
    padding-bottom: 16px;
}

h2 {
    position: relative;
    margin: 0;
    margin-bottom: 26px;

    &::after {
        position: absolute;
        left: -20px;
        top: 2px;
        content: "";
        width: 8px;
        height: 24px;
        background: #2F6CBC;
        border-radius: 0px 4px 4px 0px;
        opacity: 1;
    }
}

.recruit_top_left {
    width: calc(29.5% - 80px);
    background: #FFFFFF;
    height: 56px;
    padding: 24px 40px;
}

.recruit_top_right {
    width: 69%;
    background: #FFFFFF;
    height: 100px;
}

.recruit_top {
    margin-bottom: 20px;
    // height: 100px;
}

.recruit_top_navs {
    width: 160px;
    height: 100px;
    background: #FFFFFF;
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
}

.recruit_top_nav {
    background: #2F6CBC;

    p {
        color: #FFFFFF;
    }
}
</style>